package com.lin.filegraph.utils.parser.astutil;

import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.ASTParser;

import java.util.Hashtable;
import java.util.List;

/**
 * @description:
 * @author: linhuaixu
 * @time: 2023/5/18 11:08
 */

public class ASTCreator {
    private String projectPath;

    private ASTFileASTRequestor astFileASTRequestor;

    public ASTCreator(String projectPath, ASTFileASTRequestor astFileASTRequestor) {
        this.projectPath = projectPath;
        this.astFileASTRequestor = astFileASTRequestor;
    }

    public void createASTs() {
        ASTParser parser = ASTParser.newParser(8);
        FileManager fileManager = new FileManager(projectPath);

        List<String> listJar = fileManager.getJarFilePathList();
        String[] jar = (String[]) listJar.toArray(new String[listJar.size()]);
        String[] src = { projectPath };
        System.out.println(projectPath);
        parser.setEnvironment(jar, src, null, true);
        parser.setResolveBindings(true);
        parser.setBindingsRecovery(true);
        parser.setStatementsRecovery(true);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);

        @SuppressWarnings("unchecked")
        Hashtable<String, String> complierOptions = JavaCore.getOptions();
        JavaCore.setComplianceOptions("1.7", complierOptions);
        parser.setCompilerOptions(complierOptions);
        parser.setUnitName(projectPath);

        /*
         * String[] sourceFilePaths: paths of all *.java files in a version
         * String[] bindingKeys String[] encodings FileASTRequestor requestor
         * IProgressMonitor monitor
         */
        String[] sourcePaths = new String[fileManager.getSrcFilePathList().size()];
        fileManager.getSrcFilePathList().toArray(sourcePaths);
        parser.createASTs(sourcePaths, null, new String[0], astFileASTRequestor, null);
    }

}

